import React, { Component } from "react";
import Condition from "components/condition";
import "styles/my-account/components/invoice-goods.scss";
import { Button, Icon, InputNumber, Select } from "antd";
import { currencyPrecisionCal, messages, queryCurrencyPrecision } from "share/common";
import Space from "components/space";
import ResizeTable from "components/resize-table/resize-table";

const { Option } = Select;

class InvoiceGoods extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.value,
      isShowGoods: props.value.length > 0,
    };

    this.columns = [
      {
        title: messages("expense-1.key806") /*行总金额*/,
        dataIndex: "totalAmount",
        width: 80,
        render: (value, record, index) => {
          const precision = queryCurrencyPrecision(this.props.currencyCode);
          return (
            <InputNumber
              value={value}
              precision={precision}
              disabled={this.props.disabled}
              step={precision ? 1 / Math.pow(10, precision) : 1}
              onChange={(e) => this.onAmountChange(e, index, "totalAmount")}
              placeholder={messages("common.please.input") /*请输入*/}
            />
          );
        },
      },
      {
        title: messages("common.amount") /*金额*/,
        dataIndex: "amount",
        width: 80,
        render: (value, record, index) => {
          const precision = queryCurrencyPrecision(this.props.currencyCode);
          return (
            <InputNumber
              value={value}
              precision={precision}
              disabled={this.props.disabled}
              step={precision ? 1 / Math.pow(10, precision) : 1}
              onChange={(e) => this.onAmountChange(e, index, "amount")}
              placeholder={messages("common.please.input") /*请输入*/}
            />
          );
        },
      },
      {
        title: messages("expense-1.key69") /*税率*/,
        dataIndex: "taxRate",
        width: 120,
        render: (value, record, index) => {
          return (
            <Select
              disabled={this.props.disabled}
              value={value}
              placeholder={messages("common.select") /*请选择*/}
              onChange={(e) => this.onAmountChange(e, index, "taxRate")}
            >
              {this.props.taxRates.map((tax) => {
                return (
                  <Option value={tax.taxRateValue} key={tax.taxRateValue}>
                    {tax.taxRateKey}
                  </Option>
                );
              })}
            </Select>
          );
        },
      },
      {
        title: messages("common.tax") /*税额*/,
        dataIndex: "taxPrice",
        width: 80,
        render: (value, record, index) => {
          const precision = queryCurrencyPrecision(this.props.currencyCode);
          return (
            <InputNumber
              value={value}
              precision={precision}
              step={precision ? 1 / Math.pow(10, precision) : 1}
              onChange={(e) => this.onAmountChange(e, index, "taxPrice")}
              disabled={this.props.disabled}
            />
          );
        },
      },
      {
        title: messages("common.operation") /*操作*/,
        dataIndex: "operation",
        width: 80,
        render: (value, record, index) => {
          return (
            <section className="invoice-goods-operation">
              <div className="invoice-goods-operation-edit">
                <Condition.If value={this.state.value.length !== 1 && !this.props.disabled}>
                  <a onClick={() => this.handleDelete(index)}>{messages("common.delete") /*删除*/}</a>
                </Condition.If>
              </div>
            </section>
          );
        },
      },
    ];

    this.unshiftColumns = [
      {
        title: messages("expense-1.key70") /*项目名称*/,
        dataIndex: "goodsName",
        width: "80px",
        render: (goodsName) => goodsName || "-",
      },
      {
        title: messages("expense-1.key71") /*车牌号*/,
        dataIndex: "plateNumber",
        render: (plateNumber) => plateNumber || "-",
      },
      {
        title: messages("expense-1.key72") /*类型*/,
        dataIndex: "carType",
        render: (carType) => carType || "-",
      },
      {
        title: messages("expense-1.key73") /*通行日期起*/,
        dataIndex: "passDateFrom",
        render: (passDateFrom) => passDateFrom || "-",
      },
      {
        title: messages("expense-1.key74") /*通行日期至*/,
        dataIndex: "passDateTo",
        render: (passDateTo) => passDateTo || "-",
      },
    ];

    this.unTravalColumns = [
      {
        title: messages("expense-1.key67") /*货物或应税劳务、服务名称*/,
        dataIndex: "goodsName",
        width: "80px",
        render: (goodsName) => (
          <div
            style={{
              wordWrap: "break-word",
              wordBreak: "break-word",
              whiteSpace: "normal",
              overflow: "hidden",
              textOverflow: "ellipsis",
            }}
          >
            {goodsName || "-"}
          </div>
        ),
      },
      {
        title: messages("expense-1.key68") /*规格型号*/,
        dataIndex: "vehicleType",
        render: (vehicleType) => vehicleType || "-",
      },
      {
        title: messages("common.unit") /*单位*/,
        dataIndex: "unit",
      },
      {
        title: messages("common.number") /*数量*/,
        dataIndex: "count",
      },
      {
        title: messages("common.price") /*单价*/,
        dataIndex: "unitPrice",
        render: (unitPrice, item) =>
          unitPrice ? (Number(unitPrice) / 100).toFixed(queryCurrencyPrecision(item.vatInvoiceCurrencyCode)) : "-",
      },
    ];
  }

  componentWillReceiveProps(nextProps) {
    if ("value" in nextProps) {
      this.setState({ value: nextProps.value });
    }
  }

  componentWillMount() {
    if (this.props.fromPage === "auditCheck") {
      this.props.invoiceTypeNo !== "14"
        ? this.columns.unshift(...this.unTravalColumns)
        : this.columns.unshift(...this.unshiftColumns);
    }
  }

  onAmountChange = (e, index, word) => {
    const { value } = this.state;
    const currentLine = value[index];
    currentLine[word] = e;
    const { taxRate = 0, amount = 0, taxPrice = 0, totalAmount = 0 } = currentLine;

    if (word === "totalAmount") {
      if (taxRate)
        currentLine.taxPrice =
          currencyPrecisionCal(this.props.currencyCode, (totalAmount / (1 + taxRate)) * taxRate) || 0;
      currentLine.amount = currencyPrecisionCal(this.props.currencyCode, totalAmount - currentLine.taxPrice) || 0;
    }

    if (word === "amount") {
      if (taxRate) currentLine.taxPrice = currencyPrecisionCal(this.props.currencyCode, Number(amount) * taxRate) || 0;
      currentLine.totalAmount =
        currencyPrecisionCal(this.props.currencyCode, Number(amount) + Number(currentLine.taxPrice)) || 0;
    }

    if (word === "taxPrice") {
      currentLine.totalAmount = currencyPrecisionCal(this.props.currencyCode, Number(taxPrice) + Number(amount)) || 0;
    }

    if (word === "taxRate") {
      currentLine.taxPrice =
        currencyPrecisionCal(this.props.currencyCode, (totalAmount / (1 + taxRate)) * taxRate) || 0;
      currentLine.amount = currencyPrecisionCal(this.props.currencyCode, totalAmount - currentLine.taxPrice) || 0;
    }

    this.setState({ value }, () => this.props.onChange(value));
  };

  handleDelete = (index) => {
    const { value } = this.state;
    value.splice(index, 1);
    this.setState({ value }, () => this.props.onChange(value));
  };

  handleAddInvoiceGoods = () => {
    const { value, isShowGoods } = this.state;
    if (!isShowGoods && value[0]) {
      this.setState({ isShowGoods: true });
      return;
    }
    value.push({ taxRate: void 0, amount: 0, taxPrice: 0, totalAmount: 0 });
    this.setState({ value, isShowGoods: true });
  };

  renderAmount = (code) => {
    const { currencyCode } = this.props;
    const { value } = this.state;
    const obj = {
      amount: currencyPrecisionCal(
        currencyCode,
        value.reduce((total, item) => total + Number(item.amount), 0)
      ),
      taxPrice: currencyPrecisionCal(
        currencyCode,
        value.reduce((total, item) => total + Number(item.taxPrice), 0)
      ),
      priceTaxAmount: currencyPrecisionCal(
        currencyCode,
        value.reduce((total, item) => total + Number(item.amount) + Number(item.taxPrice), 0)
      ),
    };
    return obj[code];
  };

  render() {
    return (
      <section className="invoice-goods">
        <section className="invoice-goods-add">
          <Condition.If value={!this.props.disabled}>
            <Button type={"primary"} onClick={this.handleAddInvoiceGoods} className="animated fadeIn">
              {messages("expense-1.key772") /*添加发票行*/}
            </Button>
          </Condition.If>
          <Condition.If value={!this.state.isShowGoods}>
            <div className="invoice-goods-desc">
              <Icon type="info-circle-o" /> {messages("expense-1.key773") /*若票面有多个发票行，可点击此按钮手动添加*/}
            </div>
          </Condition.If>
        </section>
        <Condition.If value={this.state.value.length > 0 && this.state.isShowGoods}>
          <div className="invoice-goods-title">
            <Space size={"middle"}>
              <span>
                {messages("expense-1.key774") /*金额合计：*/}
                {this.props.currencyCode} {this.renderAmount("amount") || "-"}
              </span>
              <span>
                {" "}
                {messages("expense-1.key775") /*税额合计：*/}
                {this.props.currencyCode} {this.renderAmount("taxPrice") || "-"}
              </span>
              <span>
                {" "}
                {messages("expense-1.key776") /*价税合计：*/}
                {this.props.currencyCode} {this.renderAmount("priceTaxAmount") || "-"}
              </span>
            </Space>
          </div>
          <Condition.If value={this.state.isShowGoods}>
            <ResizeTable
              rowKey={(record, index) => index}
              columns={this.columns}
              dataSource={this.state.value}
              size="middle"
              bordered
              pagination={false}
              locale={{
                emptyText: this.props.blockchain
                  ? messages("expense-1.key672") /*区块链发票：国税局不支持查验，无法获取发票行信息*/
                  : messages("common.empty.text") /*暂无数据*/,
              }}
            />
          </Condition.If>
        </Condition.If>
      </section>
    );
  }
}

InvoiceGoods.propTypes = {
  value: React.PropTypes.array,
  onChange: React.PropTypes.func,
};

export default InvoiceGoods;
